import cv2
import pytesseract


def match(screen_img):
    screen_img = cv2.imread(screen_img)
    screen_img = cv2.cvtColor(screen_img, cv2.COLOR_BGR2GRAY)

    pytesseract.pytesseract.tesseract_cmd = r'D:\ocr\tesseract.exe'
    _, screen_img = cv2.threshold(screen_img, 127, 255, cv2.THRESH_BINARY)

    x = orcx(screen_img)

    y = orcy(screen_img)

    return sort(x, y)


def orcx(screen_img):
    x = []
    for i in range(0, 15):
        t = 35
        p = 133
        timg = screen_img[250:370, p + i * t:p + (i + 1) * t]

        # cv2.imshow('Result', timg)
        # cv2.waitKey(1000)
        # cv2.destroyAllWindows()
        _, timg = cv2.threshold(timg, 127, 255, cv2.THRESH_BINARY)
        result = pytesseract.image_to_string(timg, lang='eng', config=r' -c tessedit_char_whitelist=0123456789 --psm 6')
        x.append(result.split("\n"))
    return x


def orcy(screen_img):
    y = []
    for i in range(0, 15):
        t = 35
        p = 370
        timg = screen_img[p + i * t:p + (i + 1) * t, 0:200]
        # cv2.imshow('Result', timg)
        # cv2.waitKey(1000)
        # cv2.destroyAllWindows()
        # exit()
        _, timg = cv2.threshold(timg, 127, 255, cv2.THRESH_BINARY)
        result = pytesseract.image_to_string(timg, lang='eng', config=r' -c tessedit_char_whitelist=0123456789 --psm 6')
        y.append(result.split("\n"))
        # print(result)

    return y


def sort(x, y):
    tx = []
    ty = []
    for i in x:
        t = []

        for j in i:
            if j:
                t.append(int(j))
        tx.append(t)

    for i in y:
        t = []

        for j in i:
            if j:
                if int(j) > 15:
                    for m in j:
                        t.append(int(m))
                else:
                    t.append(int(j))
        ty.append(t)
    return tx, ty
